package com.gyms.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.classic.okhttp.beans.HVProjectBean;
import com.classic.okhttp.beans.HVVenueMapBean;
import com.classic.okhttp.services.IVenueService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.gyms.MyApplication;
import com.gyms.R;
import com.gyms.bean.HVVenueMyMapBean;
import com.gyms.constant.Constants;
import com.gyms.manager.LocationManger;
import com.gyms.manager.MapUtilsManger;
import com.gyms.manager.TitleManager;
import com.gyms.view.bottomview.MapSelectDialog;
import com.gyms.view.swipeback.SwipeWindowHelper;

import java.util.ArrayList;
import java.util.List;

import utils.DataUtil;
import utils.StringUtils;
import weight.loadingview.DialogUtil;

import static com.gyms.manager.TitleManager.TitleTheme.White;

/**
 * Create by Leo on 2015/12/3.
 */
public class LocationMapActivity extends AppCompatActivity implements AMap.OnMarkerClickListener, AMap.OnCameraChangeListener, LocationSource, AMapLocationListener, View.OnClickListener, AMap.OnMapClickListener {
    private LatLng mCurLatlng;
    MapView mapView;
    private AMap mAMap;
    private String address="";
    private Double latitude = 30.266093;
    private Double longitude = 120.133771;
    protected TitleManager mTitleManager;//用title管理类处理
    protected TitleManager.TitleTheme mTheme = White;
    private Context context;
    private static String mGymName;
    private View infoWindow = null;
    private static final int MAX_LINE_COUNT=25;

//    private ArrayList<HVVenueBean> mGymBeans;
    private ArrayList<Marker> mMarkers=new ArrayList<Marker>();

    private boolean isMapFromSearch;//从搜索结果页进入 展示场馆分布
    private LocationManger mLocationManger;
    private ArrayList<HVVenueMapBean> mHVVenueMapBeans=new ArrayList<>();
    private String mProjectId;
    private Dialog loadingView;
    private MapUtilsManger mMapUtilsManger;
    //定位蓝点相关
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private String mGymId;//场馆Id
    //点击地图外面  InfoWindow消失
    private Marker mCurMark;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.location_map_activity);
        context = this;
        loadingView = DialogUtil.createLoadingDialog(this, "正在加载", true);
        mLocationManger=LocationManger.getInstance(getApplicationContext());
        latitude=getIntent().getDoubleExtra(Constants.FLAG_INTENT_LATITUDE,30.266093);
        longitude=getIntent().getDoubleExtra(Constants.FLAG_INTENT_LONGITUDE,120.133771);
        address=getIntent().getStringExtra(Constants.FLAG_INTENT_ADDRESS);
        isMapFromSearch=getIntent().getExtras().getBoolean(Constants.IS_MAP_FROM_SEARCH);
        mProjectId=getIntent().getExtras().getString(Constants.FLAG_INTENT_PROJECTID);
        mMapUtilsManger=MapUtilsManger.getInstance();
        //初始化场馆的数据
        if(isMapFromSearch&&StringUtils.isNull(mMapUtilsManger.mMpProject)){
            List<HVProjectBean> mHVProjectBean = ((MyApplication) getApplication()).mHVProjectBean;
            mMapUtilsManger.mHVProjectBeans=mHVProjectBean;//初始化运动分类列表
            mMapUtilsManger.initProjectMp(mHVProjectBean);
        }

        if(!StringUtils.isNull(address)){
            address= StringUtils.toMultiLine(address,MAX_LINE_COUNT);//每隔25个字符就换行
        }
        mGymName=getIntent().getStringExtra(Constants.FLAG_INTENT_GYM_NAME);
//        mGymBeans= (ArrayList<HVVenueBean>) getIntent().getSerializableExtra(Constants.Map_List_gyms);//多个场馆的bean 将显示在地图上

        //获取地图控件引用
        mapView = (MapView) findViewById(R.id.mapview1);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        mapView.onCreate(savedInstanceState);
        mCurLatlng = new com.amap.api.maps.model.LatLng(latitude, longitude);
        mAMap = mapView.getMap();

        initMap();
        if (null != findViewById(R.id.tv_title)) {
            mTitleManager = new TitleManager(((ViewGroup) findViewById(android.R.id.content)).getChildAt(0), this, mTheme);

            if(isMapFromSearch){
                mTitleManager.setTitle("场馆地图");

            }else{
                mTitleManager.setTitle("地图");
                mTitleManager.setRightText("导航");
            }
            mTitleManager.getmRightTV().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MapSelectDialog dialog = new MapSelectDialog(context, R.style.BottomToTopAnim,String.valueOf(latitude),String.valueOf(longitude));
                    dialog.show();
                }
            });
            setBack();
        }

        setListen();

    }



    private void setListen() {
        mAMap.setOnMarkerClickListener(this);
        mAMap.setOnMapClickListener(this);
        mAMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                if(infoWindow == null) {
                    infoWindow = LayoutInflater.from(getApplicationContext()).inflate(
                            R.layout.custom_info_window, null);
                }
                render(marker, infoWindow);
                return infoWindow;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });
        mAMap.setOnCameraChangeListener(this);

        //定位蓝点
        // 设置定位监听
        mAMap.setLocationSource(this);
// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        mAMap.setMyLocationEnabled(true);
// 设置定位的类型为定位模式，有定位、跟随或地图根据面向方向旋转几种
        mAMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mapView.onSaveInstanceState(outState);
    }


    /**
     * 初始化AMap对象
     */
    private void initMap() {
            if(!isMapFromSearch){//不是从搜索页面进入直接显示
                setMapView(mAMap, latitude, longitude, DataUtil.cs(address));
            }else{//从搜索页面进入获取场馆信息
                getVenueMapList();
        }
    }

    /***
     * 获取场馆相关的数据
     */

    private void getVenueMapList() {
        loadingView.show();
        IVenueService.getVenueMapList(this, mLocationManger.getCityCode(),mProjectId , null,false, new ObjectCallback<ArrayList<HVVenueMapBean>>() {
            @Override
            public void onSuccess(ArrayList<HVVenueMapBean> response, String message) {
                loadingView.dismiss();
                if(!StringUtils.isNull(response)){
//                    mHVVenueMapBeans.addAll(response);
//                    mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mCurLatlng, 13));
                    mMapUtilsManger.setHVVenueMyMapBeans(response,mProjectId);
                    mMapUtilsManger.getCurDIstanceBeans(mCurLatlng);
                    mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mCurLatlng, 13));
//                    addMarkersToMap();
                }
            }

            @Override
            public void onErrorT(int code, ArrayList<HVVenueMapBean> response, String errorMessage) {
                loadingView.dismiss();
                mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mCurLatlng, 13));

            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                loadingView.dismiss();
                mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mCurLatlng, 13));

            }
        });
    }

    /**
     * 添加标记点组
     */

    private void addMarkersToMap() {
        ArrayList<MarkerOptions> markerOptionlst = new ArrayList<>();

//        ArrayList<HVVenueMapBean> mTempBeans =  mMapUtilsManger.mHVVenueMapBeans;
        ArrayList<HVVenueMyMapBean> mTempBeans =  mMapUtilsManger.mHVVenueMyMapBeans;

        for (HVVenueMyMapBean mGymBean:mTempBeans){

            if(mGymBean.getMarker()!=null && !mGymBean.isCanAdd())
            {
                mGymBean.getMarker().remove();
                mGymBean.setMarker(null);
            }
            else if(mGymBean.getMarker()==null && mGymBean.isCanAdd()) {

                MarkerOptions markerOption = new MarkerOptions();
                if (null != mGymBean.mHVVenueMapBean.getLatitude() && null != mGymBean.mHVVenueMapBean.getLongitude()) {
                    markerOption.position(new LatLng(mGymBean.mHVVenueMapBean.getLatitude(), mGymBean.mHVVenueMapBean.getLongitude()));
                }
                markerOption.title(mGymBean.mHVVenueMapBean.getVenueName()).snippet(mGymBean.mHVVenueMapBean.getShortAddress());
                markerOption.draggable(false);
//                markerOption.icon(com.amap.api.maps.model.BitmapDescriptorFactory.defaultMarker(com.amap.api.maps.model.BitmapDescriptorFactory.HUE_AZURE));
                //TODO
                markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(getResources(),mMapUtilsManger.getMarkIcon(mProjectId))));
                markerOption.setFlat(true);
                markerOptionlst.add(markerOption);
                mGymBean.setMarker(mAMap.addMarker(markerOption) );
            }
        }



    }

    @Override
    protected void onResume() {
        super.onResume();

        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if(isMapFromSearch){//只有搜索进来的时候才clear
            mMapUtilsManger.mHVVenueMyMapBeans.clear();
        }
        mGymName=null;
        if(null != mlocationClient){
            mlocationClient.onDestroy();
        }
    }

    /**
     * 在地图上添加marker标记
     *
     * @param aMap
     * @param latitude
     * @param longitude
     * @param address
     */
    public void setMapView(AMap aMap, double latitude, double longitude, String address) {
        mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mCurLatlng, 13));
        com.amap.api.maps.model.MarkerOptions markerOptions = new com.amap.api.maps.model.MarkerOptions();
        markerOptions.position(mCurLatlng);
        markerOptions.anchor(0.5f, 0.5f);
        markerOptions.title(mGymName).snippet(address);
        markerOptions.icon(com.amap.api.maps.model.BitmapDescriptorFactory.defaultMarker(com.amap.api.maps.model.BitmapDescriptorFactory.HUE_AZURE));
        markerOptions.draggable(true);
        Marker marker = aMap.addMarker(markerOptions);
        marker.showInfoWindow();// 设置默认显示一个infowinfow
//        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mCurLatlng, 18));
    }

    /**
     * 返回键
     */
    public void setBack() {
        View mBack = mTitleManager.setBack();
        if (mBack != null) {
            mBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }

    //-------------------------滑动返回Star--------------------------
    protected SwipeWindowHelper mSwipeWindowHelper;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(!supportSlideBack()) {
            return super.dispatchTouchEvent(ev);
        }
        if(mSwipeWindowHelper == null) {
            mSwipeWindowHelper = new SwipeWindowHelper(getWindow());
        }
        return mSwipeWindowHelper.processTouchEvent(ev) || super.dispatchTouchEvent(ev);
    }

    /**
     * 是否支持滑动返回
     *
     * @return
     */
    protected boolean supportSlideBack() {
        return true;
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        mCurMark=marker;//实现点击外面
        if(!isMapFromSearch){
            return false;
        }
        if(!StringUtils.isNull(mMapUtilsManger.mHVVenueMyMapBeans)){
            for(int i=0;i<mMapUtilsManger.mHVVenueMyMapBeans.size();i++){
                if (marker.equals(mMapUtilsManger.mHVVenueMyMapBeans.get(i).getMarker())) {
                    if (mAMap != null) {
                        mGymName=mMapUtilsManger.mHVVenueMyMapBeans.get(i).mHVVenueMapBean.getVenueName();
                        address=StringUtils.toMultiLine(mMapUtilsManger.mHVVenueMyMapBeans.get(i).mHVVenueMapBean.getShortAddress(),MAX_LINE_COUNT);
                         mGymId=mMapUtilsManger.mHVVenueMyMapBeans.get(i).mHVVenueMapBean.getVenueId();

                    }
                }
            }
        }

        return false;
    }

    /**
     * 自定义infowinfow窗口
     */
    public void render(Marker marker, View view) {
     //如果想修改自定义Infow中内容，请通过view找到它并修改
        TextView mTitleView= (TextView) view.findViewById(R.id.tv_adr_title);
        TextView mContentView= (TextView) view.findViewById(R.id.tv_adr_content);
        ImageView mIvGymNext= (ImageView) view.findViewById(R.id.iv_gym_next);
        if(!isMapFromSearch){
            mIvGymNext.setVisibility(View.GONE);
        }
//        LinearLayout mLlContentView= (LinearLayout) view.findViewById(R.id.ll_adr_content);
//        mContentView.setTag(mGymId);
        mContentView.setOnClickListener(this);
        mIvGymNext.setOnClickListener(this);
        mTitleView.setText(mGymName);
        mContentView.setText(address);
    }
    //----------------------高德地图获取当前屏幕中心点的经纬度－－－－－－－－－－－－－－

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {




    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        if(!isMapFromSearch){
            return;
        }
        LatLng mTagLatlng=cameraPosition.target;
//        mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mTagLatlng, 18));
        mMapUtilsManger.getCurDIstanceBeans(mTagLatlng);//符合当前距离的范围内


        addMarkersToMap();

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
//            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();//启动定位
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null&&aMapLocation != null) {
            if (aMapLocation != null
                    &&aMapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode()+ ": " + aMapLocation.getErrorInfo();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_gym_next:
            case R.id.tv_adr_content://点击跳转
                if (!isMapFromSearch) {
                    return;
                }
                Intent mItent =new Intent(LocationMapActivity.this,GymDetailActivity.class);
                Bundle mBundle=new Bundle();
                mBundle.putString(Constants.FLAG_INTENT_VENUEID, mGymId);
                mItent.putExtras(mBundle);
                startActivity(mItent);
                break;
        }
    }

    @Override
    public void onMapClick(LatLng latLng) {
        if(mCurMark.isInfoWindowShown()){
            mCurMark.hideInfoWindow();//这个是隐藏infowindow窗口的方法
        }
    }

    //-------------------------滑动返回End--------------------------


}
